<%--
  Created by IntelliJ IDEA.
  User: sicilin
  Date: 2017/8/3
  Time: 11:04
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@include file="../commons-easyui.jsp"%>
<html>
<head>
    <title>用户管理</title>
    <script type="text/javascript" src="<%=basePath%>common/script/customize/customize-old.js"></script>
    <script type="text/javascript" src="<%=basePath%>common/script/customize/object/object.js"></script>
    <style type="text/css">
        #userForm > div{
            margin: 10px 0px;
        }
        #userForm > div > .easyui-validatebox{
            height:25px;
        }
        .roleHave {
            background: #99CCFF;
            color: #000;
        }
    </style>

    <script type="text/javascript">
        /*-------------- 全局变量 --------------*/
        var sexMapped = ['保密','男','女'];
        var statusMapped = ['禁用','启用'];
        var userFormMode = '';

        /*-------------- 页面加载执行 --------------*/
        $(document).ready(function () {
            initUserTable();
            initCompanyCombo();
        });

        function initCompanyCombo(){
            if(currentUser.account != 'admin'){
                $('#selectCompanyDiv').remove();
                return;
            }

            tmsObject.treeCombo($('#companyCombo'),["mainCompany","ourCompany","upCompany","downCompany"],true);
        }

        function addUserRole(){
            var selectUser = getSelectUser();
            if($.isEmptyObject(selectUser)){
                $.messager.alert('警告','没有选择的用户！','warning',emptyFn());
                return false;
            }
            var selectOweRoles = $('#roleTable').datagrid('getSelections');
            if($.isEmptyObject(selectOweRoles)){
                $.messager.alert('警告','没有选择要添加的角色！','warning',emptyFn());
                return false;
            }

            var param = [];
            $.each(selectOweRoles,function (index,key) {
                param.push({'userId':selectUser.userId,'roleId':selectOweRoles[index].roleId});
            });
            $.ajax({
                url:basePath+'userAction/addUserRole.json'
                ,type:'post'
                ,data:JSON.stringify(param)
                ,dataType:'json'
                ,contentType:'application/json'
                ,success:function (ajaxResponse) {
                    var data = getAjaxReturnData(ajaxResponse);
                    if(!isBlank(data)){
                        alert('success');
                        loadOweRole(selectUser.userId);
                    }
                }
            });

        }

        function searchUserRole(mode,userId){
            $('#userRoleList').datalist(mode,{'userId':userId});
        }

        function loadOweRole(userId){
            $('#roleTable').datagrid('load',{"userId":userId});
        }

        function initRoleTable(){
            var selectUser = getSelectUser();
            if($.isEmptyObject(selectUser)){
                $.messager.alert('警告','没有选择的用户！','warning',emptyFn());
                return false;
            }
            var initialization = $('#roleTable').data('initialization');
            if(initialization == 'complete'){
                loadOweRole(selectUser.userId);
                return;
            }

            $('#roleTable').datagrid({
                url:basePath+'userAction/getUserOweRole.json'
                ,queryParams:{"userId":selectUser.userId}
                ,method:'post'
                ,rownumbers:true
                ,fit:true
                ,border:false
                ,toolbar:'#roleToolbar'
                ,columns:[[
                    {field:'roleCode',title:'角色编号'}
                    ,{field:'roleName',title:'角色名称'}
                    ,{field:'description',title:'角色说明'}
                ]]
            });
            $('#roleTable').data('initialization','complete');
        }

        function initUserRoleList(userId){
            $('#userRoleList').datalist({
                url:basePath+'userAction/getUserRole.json'
                ,queryParams:{'userId':userId}
                ,method:'post'
                ,lines:true
                ,valueField:'roleId'
                ,textField:'roleCode'
                ,toolbar:'#roleListToolbar'
                ,fit:true
                ,border:false
                ,textFormatter:function (value,row,index) {
                    return row.roleName +'('+row.roleCode+')';
                }
            });
        }

        function removeUserRole(){
            var selectRoles = $('#userRoleList').datalist('getSelections');
            if(isBlank(selectRoles)){
                easyuiAlert("请先选择角色","warning");
                return;
            }
            var param = [];
            var selectUser = getSelectUser();
            $.each(selectRoles,function (index,key) {
                param.push({'userId':selectUser.userId,'roleId':selectRoles[index].roleId});
            });
            $.messager.confirm("确认","请确认是否移除这些角色",function(confirm){
                if(confirm){
                    tmsAjax({
                        url:basePath+'userAction/removeUserRole.json'
                        ,type:'post'
                        ,data:JSON.stringify(param)
                        ,dataType:'json'
                        ,isResultState:true
                    });
                }
            });
        }


        function searchUser(){
           var text =  $('#searchText').textbox('getText');
            $('#userTable').datagrid('load',{'text':text});
        }

        function initUserTable(){
            $('#userTable').datagrid({
                url:basePath+'userAction/searchUserLimit.json'
                ,method:'post'
                ,queryParams:{'text':''}
                ,pagination:true
                ,striped:true
                ,fit:true
                ,rownumbers:true
                ,idField:'userId'
                ,singleSelect:true
                ,pageSize:20
                ,pageList:[20,50,100]
                ,border:false
                ,toolbar:'#tableToolbar'
                ,columns:[[
                    {field:'company',title:'所属公司',width:75,formatter:function(value,row,index){
                        return value.companyName+"("+value.companyCode+")";

                    }}
                    ,{field:'account',title:'账号',width:75}
                    ,{field:'name',title:'名称',width:75}
                    ,{field:'telephone',title:'手机号',width:75}
                    ,{field:'sex',title:'性别',width:40,formatter:function(value,row,index){
                        return sexMapped[value];
                    }}
                    ,{field:'email',title:'电子邮箱',width:75}
                    ,{field:'qq',title:'QQ',width:75}
                    ,{field:'address',title:'地址',width:75}
                    ,{field:'status',title:'状态',width:40,formatter:function (value,row,index) {
                        return statusMapped[value];
                    }}
                    ,{field:'createTime',title:'创建时间',width:117,formatter:function (value,row,index) {
                        return formatterJSONTime(value);
                    }}
                    ,{field:'updateTime',title:'更新时间',width:117,formatter:function (value,row,index){
                        return formatterJSONTime(value);
                    }}
                ]]
                ,onSelect:function (index,row) {
                    if($('#userRoleList').data('initialization') != 'complete'){
                        initUserRoleList(row.userId);
                        $('#userRoleList').data('initialization','complete');
                        return;
                    }
                    searchUserRole('reload',row.userId);
                }
            });
        }

        function setFormSubmitMode(mode){
            $('#userForm').form('clear');
            if(mode == 'add'){
                $('#sex').combobox('select',0);
            }else if(mode == 'edit'){
                var selectUser = getSelectUser();
                if($.isEmptyObject(selectUser)){
                    $.messager.alert('警告','没有选择的用户！','warning',emptyFn());
                    return false;
                }
                tmsObject.setCombo($('#companyCombo'),selectUser.company.companyId,selectUser.company.companyCode,selectUser.company.companyName);
                $('#account').val(selectUser.account);$('#account').validatebox('validate');
                $('#name').val(selectUser.name);$('#name').validatebox('validate');
                $('#telephone').val(selectUser.telephone);
                $('#sex').combobox('select',selectUser.sex);
                $('#email').val(selectUser.email);
                $('#qq').val(selectUser.qq);
                $('#address').val(selectUser.address);
            }
            userFormMode = mode;
        }

        function getSelectUser() {
            return $('#userTable').datagrid('getSelected');
        }
        function relaodTable() {
            var text =  $('#searchText').textbox('getText');
            $('#userTable').datagrid('reload',{'text':text});
        }

        function submitUserForm() {
            var param = getJSONFormData('userForm');
            if(userFormMode == 'add'){
                $.ajax({
                    url:basePath+'userAction/saveUser.json'+ (currentUser.account == 'admin'?'?admin=true' : '')
                    ,data:JSON.stringify(param)
                    ,type:'post'
                    ,contentType:'application/json'
                    ,dataType:'json'
                    ,success:function (ajaxData) {
                       var data = getAjaxReturnData(ajaxData);
                        if(!isBlank(data)){
                            $.messager.alert("成功","添加用户成功！",'info',emptyFn());
                            closeDialog('userDialog');
                            relaodTable();
                        }
                    }
                });
            }else if(userFormMode == 'edit'){
                var selectUser = getSelectUser();
                param.userId = selectUser.userId;
                $.ajax({
                    url:basePath+'userAction/updateUser.json'
                    ,data:JSON.stringify(param)
                    ,type:'post'
                    ,contentType:'application/json'
                    ,dataType:'json'
                    ,success:function (ajaxData) {
                        var data = getAjaxReturnData(ajaxData);
                        if(!isBlank(data)){
                            $.messager.alert("成功","修改用户成功！",'info',emptyFn());
                            closeDialog('userDialog');
                            relaodTable();
                        }
                    }
                });
            }
        }

        function switchStatus(){
            var selectUser = getSelectUser();
            if(isBlank(selectUser)){
                easyuiAlert('请先选择用户！','warning');
                return;
            }
            var mode = 'enable';
            if(selectUser.status == 1){
                mode = 'disable';
            }
            var modeText = {"enable":"启用","disable":"禁用"};
            $.messager.confirm("确认操作","确定"+modeText[mode]+selectUser.account+"用户？",function(confirm){
                if(confirm){
                    tmsAjax({
                        url:basePath+'userAction/switchStatus.json?'+mode+'&userId='+selectUser.userId
                        ,type:'post'
                        ,dataType:'json'
                        ,isResultState:true
                        ,success:function(data){
                            console.info(data);
                        }
                    });
                }
            });

        }
    </script>
</head>
<body>
    <div class ="easyui-layout" data-options="fit:true">
        <div data-options="region:'east',title:'用户所有角色',split:true" style="width:300px;">
            <ul id = "userRoleList"></ul>
        </div>
        <div data-options="region:'center',title:'用户管理'" style="background:#eee;">
            <table id="userTable"></table>
        </div>
    </div>

    <!-- 工具栏 -->
    <div id = "tableToolbar">
        <input id ="searchText" class="easyui-textbox" data-options="buttonIcon:'icon-search',prompt:'关键字（账号，名称）',onClickButton:searchUser" style="width:200px;" />
        <a class="easyui-linkbutton" data-options="iconCls:'icon-add'" onclick="openOrInitDialog('userDialog','账号管理',null,null,setFormSubmitMode,'add')" style="margin-left: 10px;">新建账号</a>
        <a class="easyui-linkbutton" data-options="iconCls:'icon-edit'" onclick="openOrInitDialog('userDialog','账号管理',null,null,setFormSubmitMode,'edit')" >修改账号</a>
        <a class="easyui-linkbutton" data-options="iconCls:'icon-lock'">重置密码</a>
        <a class="easyui-linkbutton" data-options="iconCls:'icon-lock'" onclick="switchStatus()">禁/启用</a>
    </div>
    <div id = "roleListToolbar">
        <a class="easyui-linkbutton" data-options="iconCls:'icon-lock'" onclick="openOrInitDialog('userRoleDialog','添加用户角色',null,null,initRoleTable)" style="margin-left: 10px;">添加用户角色</a>
        <a class="easyui-linkbutton" data-options="iconCls:'icon-cancel'" onclick="removeUserRole()" style="margin-left: 10px;">移除角色</a>
    </div>
    <div id = "roleToolbar">
        <a class="easyui-linkbutton" data-options="iconCls:'icon-add'" onclick="addUserRole()">添加</a>
    </div>

    <!-- 新建/修改 账号dialog -->
    <div id = "userDialog" style="padding:10px;width: 300px;height:380px;display: none;">
        <form id = "userForm">
            <div id="selectCompanyDiv">
                <label>所属公司</label>
                <input id = "companyCombo" name="companyId" />
            </div>
            <div>
                <label>账号：</label>
                <input id="account" class="easyui-validatebox textbox" data-options="required:true,tipPosition:'right'" name="account" />
            </div>
            <div>
                <label>名称：</label>
                <input id="name" class="easyui-validatebox textbox" data-options="required:true,tipPosition:'right'" name="name" />
            </div>
            <div>
                <label>手机号：</label>
                <input id="telephone" class="easyui-validatebox textbox" name="telephone"/>
            </div>
            <div>
                <label>性别：</label>
                <select id = "sex" class="easyui-combobox" data-options="editable:false,required:true" name="sex" style="width: 100px;">
                    <option value="0" selected>保密</option>
                    <option value="1">男</option>
                    <option value="2">女</option>
                </select>
            </div>
            <div>
                <label>电子邮箱：</label>
                <input id="email" class="easyui-validatebox textbox" name="email"/>
            </div>
            <div>
                <label>QQ：</label>
                <input id="qq" class="easyui-validatebox textbox" name="qq"/>
            </div>
            <div>
                <label>地址：</label>
                <input id="address" class="easyui-validatebox textbox" name="address"/>
            </div>


        </form>
        <div style="height:30px;margin-top: 20px;">
            <a class="easyui-linkbutton" data-options="iconCls:'icon-ok',fit:true" onclick="submitUserForm()">提交</a>
        </div>
    </div>

    <div id="userRoleDialog" style="display: none;width:500px; height: 300px;">
        <table id = "roleTable"></table>
    </div>
</body>
</html>
